/**
 * 主题配置提供者组件
 * 负责管理应用的主题设置，提供主题切换和自定义功能
 */
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { ConfigProvider, theme } from 'antd';
import type { ThemeConfig } from 'antd';
import { DEFAULT_THEME, loadThemeFromStorage, saveThemeToStorage } from '../utils/themeUtils';

/**
 * 主题配置接口
 * 定义应用主题的核心设置项
 */
export interface ThemeSettings {
  /** 主题主色调 */
  colorPrimary: string;
  /** 主题类型：亮色或暗色 */
  themeType: 'light' | 'dark';
  /** 是否使用紧凑模式 */
  useCompact: boolean;
}

/**
 * 主题上下文接口
 * 定义ThemeContext提供的值和方法
 */
interface ThemeContextType {
  themeSettings: ThemeSettings;
  updateThemeColor: (color: string) => void;
  toggleThemeType: (type: 'light' | 'dark') => void;
  toggleCompactMode: (compact: boolean) => void;
}

/**
 * 创建主题上下文
 */
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

/**
 * 主题配置提供者组件实现
 */
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  /**
   * 从localStorage加载主题配置
   */
  const [themeSettings, setThemeSettings] = useState<ThemeSettings>(() => {
    try {
      // 直接从localStorage获取并解析设置
      const saved = localStorage.getItem('appSettings');
      if (saved) {
        const settings = JSON.parse(saved);
        return {
          colorPrimary: settings.themeColor || settings.colorPrimary || DEFAULT_THEME.colorPrimary,
          themeType: (settings.themeType || DEFAULT_THEME.themeType) as 'light' | 'dark',
          useCompact: !!settings.useCompactTheme || !!settings.useCompact,
        };
      }
    } catch (error) {
      console.error('Failed to load theme settings:', error);
    }
    return DEFAULT_THEME;
  });

  /**
   * 监听主题设置变化
   * 当主题设置更新时，保存到localStorage
   */
  useEffect(() => {
    saveThemeToStorage(themeSettings);
  }, [themeSettings]);

  /**
   * 创建Ant Design主题配置（使用CSS变量模式）
   * @param settings 主题设置
   * @returns Ant Design主题配置对象
   */
  const createAntdThemeConfig = useCallback((settings: ThemeSettings): ThemeConfig => {
    // 选择算法
    const baseAlgorithm = settings.themeType === 'dark' 
      ? theme.darkAlgorithm 
      : theme.defaultAlgorithm;
    
    // 组合算法（如果需要紧凑模式）
    const algorithm = settings.useCompact 
      ? [baseAlgorithm, theme.compactAlgorithm] 
      : baseAlgorithm;

    return {
      // 启用CSS变量模式
      cssVar: {},
      token: {
        colorPrimary: settings.colorPrimary,
      },
      algorithm
    };
  }, []);

  /**
   * 更新主题主色调
   * @param color 新的主色调值
   */
  const updateThemeColor = useCallback((color: string) => {
    setThemeSettings(prev => ({ ...prev, colorPrimary: color }));
  }, []);

  /**
   * 切换主题类型（亮色/暗色）
   * @param type 目标主题类型
   */
  const toggleThemeType = useCallback((type: 'light' | 'dark') => {
    setThemeSettings(prev => ({ ...prev, themeType: type }));
  }, []);

  /**
   * 切换紧凑模式
   * @param compact 是否启用紧凑模式
   */
  const toggleCompactMode = useCallback((compact: boolean) => {
    setThemeSettings(prev => ({ ...prev, useCompact: compact }));
  }, []);

  // 准备主题上下文值
  const contextValue: ThemeContextType = {
    themeSettings,
    updateThemeColor,
    toggleThemeType,
    toggleCompactMode,
  };

  // 创建Ant Design主题配置
  const antdThemeConfig = createAntdThemeConfig(themeSettings);

  return (
    <ThemeContext.Provider value={contextValue}>
      <ConfigProvider theme={antdThemeConfig}>
        {children}
      </ConfigProvider>
    </ThemeContext.Provider>
  );
};

/**
 * 使用主题上下文的Hook
 */
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};